// pages/goods_detail/index.js
const WxParse = require('../../wxParse/wxParse.js')
import {
    getGoodsDetail,
} from "../../api/goods.js"
import {
    formatDate
} from "../../utils/util.js"
import {
    getNavigationbar,
} from "../../api/index.js"
import {
    getReMallShopping,
} from "../../api/cart.js"
Page({
    options: {
        styleIsolation: "shared"
    },

    /**
     * 页面的初始数据
     */
    data: {
        //跳转类型（1、不做跳转 2、跳转到具体的链接 3、按具体的条件跳转 4、跳转到具体的商品详情 7,新人专区 8、新品专区 9、特卖活动 10、秒杀活动 11、跳转至品牌促销活动 12、换购专区 13、跳转优惠券 15、集采专区 14、一件代发 15、跳转至精选品牌 16、跳转至秒杀活动具体商品详情页 17、跳转至特卖活动具体商品详情页 18、跳转至新人活动具体商品详情页 19、跳转至新品专区具体商品详情页 20，跳转至专区，
        list: [],
        detailType: "",
        scrollViewHeight: 0,
        swiperList: [],
        autoplay: true,
        goodsInfo: {},
        activity: [],
        saleTime: {},
        obj: {},
        isSpecs: false,
        isPromotion: false,
        isAhow: false,
        isAddress: false,
        address: "",
        specs: 0,
        numCome:1,
        params: {},
        richtext: null,
        property: [],comityid:'',
        number: 0, // 规格选择数量
        START: false, // 活动开始状态
        timer: null, // 定时器
        sysTime: 0, // 系统时间
        staTime: 0, // 开始时间
        endTime: 0, // 结束时间
        cartGoodDetail: {},
        btnText: "",
        confirmText: "",
        closeFn: "",
        numGood:0,
        // 规格弹框
        isSpecifications: false,
        specificationsData: {},
        addressId: ""

    },
    onConfirm() {
        console.log('444', 1)
        this.setData({
            isPromotion: false
        })
    },
    onClickLeft() {

        const pages = getCurrentPages();
        if (pages.length > 1) {
            wx.navigateBack();
        } else {
            wx.reLaunch({
                url: '/pages/index/index'
            });
        }

    },
    
    handleShopCart() {
        wx.reLaunch({
            url: `/pages/goods_cart/index`,
        })
    },
    /**
     * 获取商品详情信息
     * @param {*} params 
     */
    getHttpGoodsDetail(params) {

        getGoodsDetail({
            act: params.act,
            id: params.goodsId,
        }).then(res => {
            console.log('商品详情-->>>', res)
            if (res) {
                this.data.comityid = res.id
                const that = this
                let activity
                if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
                    res.price = '***'
                    res.sellprice = '***'
                    res.marketprice = '***'
                }
                wx.nextTick(() => {
                    const photos = []
                    // 判断轮播图片是否存在
                    if (res.photos && res.photos.length > 0) {
                        // 遍历图片信息数组，转换所对应渲染格式
                        res.photos.forEach(item => {

                            photos.push({
                                goodsid: item.goodsid,
                                id: item.id,
                                thumb: item.photo,
                                sort: item.sort,
                                type: item.type,
                            })
                        })
                    } else {
                        let thumb = res.thumb
                        if (!thumb.startsWith("http")) {
                            thumb = "https://static.chonglaoban.cn" + thumb
                        }
                        photos.push({
                            thumb: thumb,
                        })
                    }
                    // 判断商品规格是否存在
                    if (res.property) {
                        // 遍历商品规格

                        console.log(res.property)
                        res.property.forEach(item => {
                            item.number = 0
                            if (item.child.length > 0) {
                                this.data.property = item.child
                                item.child.forEach(child => {
                                    child.number = 0
                                })
                            } else {

                                let arr = []
                                arr.push(item)
                                this.data.property = arr

                            }
                        })
                        console.log(this.data.property)
                        res.propertyname = this.data.property[0].property_name
                        res.propertyid = this.data.property[0].id
                    }

                    // 判断商品活动信息是否存在
                    if (res.activity) {
                        const {
                            brand_activity,
                            goods_activity,
                            mix_activity,
                        } = res.activity
                        if (brand_activity.length > 0) {
                            activity = brand_activity
                        }
                        if (goods_activity.length > 0) {
                            activity = goods_activity
                        }
                        if (mix_activity.length > 0) {
                            activity = mix_activity
                        }
                        this.data.list = res.activity
                    }
                    if (activity) {
                        activity[0].lists.forEach(item => {
                            Object.assign(item, {
                                is_selected: true
                            })
                            item.offerTitle = this.parseTtile(item)
                        })
                    }
                    console.log('1', this.data.list)
                    if (this.data.list.length != 0) {
                        this.data.list.brand_activity.forEach(element => {
                            element.lists.forEach(item => {
                                Object.assign(item, {
                                    is_selected: true
                                })
                                item.offerTitle = this.parseTtile(item)
                            });
                        });
                        this.data.list.goods_activity.forEach(element => {
                            element.lists.forEach(item => {
                                Object.assign(item, {
                                    is_selected: true
                                })
                                item.offerTitle = this.parseTtile(item)
                            });
                        });
                        this.data.list.mix_activity.forEach(element => {
                            element.lists.forEach(item => {
                                Object.assign(item, {
                                    is_selected: true
                                })
                                item.offerTitle = this.parseTtile(item)
                            });
                        });
                    }

                    console.log(' this.data.list = res.activity', this.data.list)
                  
                    // 渲染商品信息
                    that.setData({
                        swiperList: photos,
                        goodsInfo: res,
                        list: this.data.list,
                        activity: activity,
                        property: this.data.property,
                        staTime: formatDate(res.starttime * 1000),
                        endTime: res.endtime,
                        sysTime: res.system_time,
                    })
                    console.log("-------------------", this.data.goodsInfo.property)
                    // 渲染富详情文本
                    var article = res.content
                    WxParse.wxParse('article', 'html', article, that, 5);
                    // 判断当前是否为秒杀商品详情页
                    if (this.data.detailType == '10') {
                        // 获取当前时段 判断对比秒杀活动每天开始时间段执行对应条件逻辑
                        const HH = new Date().getHours()
                        if (HH > parseInt(res.cuteverystarttime)) {
                            this.downTimeFormat()
                            this.setData({
                                START: true
                            })
                        } else {
                            this.setData({
                                START: false
                            })
                        }
                    }
                })
            }
        })
    },
    /**
     * 秒杀倒计时回调函数方法
     * @param {*} date 
     */
    downTimeFormat() {
        this.data.timer = setInterval(() => {
            // 获取当前时间，同时得到活动结束时间数组
            let newTime = new Date().getTime();
            let endTime = this.data.endTime * 1000;
            // 对结束时间进行处理渲染到页面
            let setTime = null;
            let time = (endTime - newTime) / 1000;
            // 获取天、时、分、秒
            let DD = parseInt(time / (60 * 60 * 24));
            let HH = parseInt(time % (60 * 60 * 24) / 3600);
            let MM = parseInt(time % (60 * 60 * 24) % 3600 / 60);
            let SS = parseInt(time % (60 * 60 * 24) % 3600 % 60);
            setTime = {
                DD: this.timeFormat(DD),
                HH: this.timeFormat(HH),
                MM: this.timeFormat(MM),
                SS: this.timeFormat(SS)
            }
            this.setData({
                saleTime: setTime
            })
        }, 1000)
    },
    timeFormat(param) { //小于10的格式化函数
        return param < 10 ? '0' + param : param;
    },
    /**
     * 选择促销回调函数方法
     */
    handlePromotion() {
        console.log('12', this.data.activity)
        this.setData({
            isPromotion: true,
            activity: this.data.activity
        })
    },

    /**
     * 添加商品数量回调函数方法
     */
    handlePlusAdd(e) {
        let {
            index,
            type,
            value,
        } = e.currentTarget.dataset
        console.log("-------------", e, index, value, type, this.data.goodsInfo)

        let good = this.data.goodsInfo
        if (index == undefined) {
            index = 0
        }
        console.log('("-------------",', good.property[index].number)
        if (type == 'child') {
            good.property.forEach(pro => {
                if (pro.property_name == value.property_name) {
                    pro.child[index].number += 1
                }
            })
        } else {
            good.property[index].number += 1
        }
        console.log('good2',good)
        this.setData({
            goodsInfo: good
        })
    },
    /**
     * 选择规格数量回调函数方法
     * @param {*} e 
     */
    handleStepChange(e) {
        let val = e.detail.value
        const {
            index,
            type,
            value,
        } = e.currentTarget.dataset
        this.data.numCome = val
        console.log("-------------", val)
        console.log("-------------", index, type, value)
        let good = this.data.goodsInfo
        if (type == 'child') {
            good.property.forEach(pro => {
                if (pro.property_name == value.property_name) {
                    pro.child[index].number = val
                }
            })
        } else {
            good.property[index].number = val
        }


        console.log('goodsInfo',good)
        this.data.goodsInfo = good
        this.setData({
            goodsInfo: good
        })
    },
    /**
     * 供应商
     */
    handleSupplier(event) {
        let obj = {
            ...event.currentTarget.dataset.value,
            name: event.currentTarget.dataset.value.brand_name,
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    /**
     * 选择规格回调函数方法
     */
    handleSelSpecs(e) {
        const {
            value
        } = e.currentTarget.dataset

        this.setData({
            isSpecifications: true,
            specificationsData: value,
            confirmText: 'specificationsConfirm',
            closeFn: 'close'
        })
    },
    //  规格的按钮确定
    specificationsConfirm() {
        this.setData({
            isSpecifications: false,
        })
    },
    // 关闭规格
    close() {
        this.setData({
            isSpecifications: false,
        })
    },
    changeSpec(e) {
        this.data.goodsInfo.propertyname = e.detail.propertyname
        this.data.goodsInfo.propertyid = e.detail.propertyid
        this.setData({
            isSpecifications: false,
            goodsInfo: this.data.goodsInfo
        })
    },
    // 新人
    handlnPay(e) {
        console.log('e',e)
        let val = e.currentTarget.dataset.value
        if(val.has_inventorys == '0') {
		
            wx.showModal({
                title: '提示',
                content: '已抢光',
                showCancel: false,
              });
              
                  
        }else {
            let data = {
                goodsid:val.goodsid,
                has_inventorys: val.has_inventorys,
                id: val.id,
                marketprice: val.marketprice,
                price: val.price,
                property_price: val.property_price,
                propertyid: val.propertyid,
                thumb: val.thumb,
            }
            console.log('提交',data)
            wx.navigateTo({
                url: `/subpackages/pages/confirm_order_sh/index?data=` + JSON.stringify(data)
            })  
        }
        
    },
    /**
     * 获取收货地址
     */
    getAddress() {
        getGoodsDetail({
            act: "addressres",
            type: "getlist",
        }).then(res => {
            if (res) {
                res.forEach(item => {
                    item.userAddress = item.province + item.city + item.county
                })
                let addr = res.find(item => item.is_default == "1")
                wx.nextTick(() => {
                    this.setData({
                        addressList: res,
                        address: addr.userAddress,
                        addressId: addr.id

                    })
                })
            }
        })
    },
    /**
     * 选择配送地址回调函数方法
     */
    handleSelAddress() {
        wx.nextTick(() => {
            this.setData({
                isAddress: true,
            })
        })

    },

    check(e) {
        console.log('点击', e)
        // this.setData({
        //     isAddress: false,
        //     address: e.detail.userAddress
        // })
        let value = e.detail
        console.log('点击', value)
        getNavigationbar({
            act: "addressres",
            type: "editor",
            id: value.id,
            truename: value.truename,
            phone: value.phone,
            province: value.province,
            city: value.city,
            county: value.county,
            town: value.town,
            provinceId: value.provinceId,
            cityId: value.cityId,
            countyId: value.countyId,
            townId: value.townId,
            address: value.address,
            is_default: '1'
        }).then(res => {
            console.log('切换地方', res)
            if (res) {
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        });
                    });
                } else {
                    let title = '添加成功';
                    if (value.id) {
                        title = '编辑成功';
                    }
                    this.setData({
                        isShow: false,
                        isAddress: false,
                        address: e.detail.userAddress,
                        address: e.detail.userAddress
                    })
                    wx.showTabBar()
                    // this.onLoad()

                }
            }
        })
    },
    cxcheck(e) {

        this.data.activity[0].lists.forEach(item => {
            item.is_selected = 0
            if (item.id == e.detail.id) {
                item.is_selected = 1
            }
        })
        this.setData({
            isPromotion: false,
            activity: this.data.activity
        })

    },
    /**
     * 促销标题
     */
    parseTtile(value) {
        let actstr = ""
        value.buy = value.buy.replaceAll(".00", "")
        value.derate = value.derate.replaceAll(".00", "")
        switch (value.type) {
            case "1":
                actstr = "满" + value.buy + "元减" + value.derate + "元"
                break
            case "2":
                actstr = "满" + value.buy + "元送" + value.derate + "件"
                break
            case "3":
                actstr = value.buy + "送" + value.derate
                break
            case "4":
                actstr = value.buy + "件" + value.derate / 10 + "折"
                break
            case "5":
                actstr = "满" + value.buy + "元打" + value.derate / 10 + "折"
                break
            case "6":
                actstr = "满" + value.buy + "送" + value.derate
                break
        }
        return actstr
    },

    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        wx.getSystemInfo({
            success: function (res) {
                const windowHeight = res.windowHeight + 70;
                console.log('手机屏幕高度：', windowHeight);

                // 进行适配操作，例如设置元素高度为屏幕高度的一半
                const halfScreenHeight = windowHeight / 2;
                console.log('屏幕高度的一半：', halfScreenHeight);
                that.setData({
                    scrollViewHeight: windowHeight - 155
                })
            }
        });
    },
    getShoppingCartList(item) {
        getNavigationbar({
            act: 'getcartsp',

        }).then(res => {
            console.log('购物车列表-一件代发', res)
            this.setData({
                numGood: res.numbers
            })

        });
    },
     /**
     * 选择商品规格加入购物车回调函数方法
     */
    handleJoinCart(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log("gouwu", value)
        if (value.has_inventorys == '0') {
            return
        }
     
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
        // getNavigationbar({
        //     act: 'good_detail',
        //     id: value.goodsid || value.id
        // }).then(res => {

        this.setData({
            isSpecs: true,
            cartGoodDetail: this.data.goodsInfo,
            btnText: "加入购物车",
            confirmText: "handleConfirm",
        })
       
    },
    /**
     * 选择商品规格加入购物车回调函数方法
     */
    handleJoit(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log("gouwu", e.currentTarget.dataset)
        if (value.has_inventorys == '0') {
            return
        }
        // this.setData({
        //     number: this.data.number
        // })
        if (this.data.obj.shop_status == 0 || this.data.obj.shop_status == 1) {
            this.setData({
                isAhow: true,
            })
            return
        }
      let data = []
        this.data.goodsInfo.property.forEach(item => {
            item.child.forEach(childItem => {
              if (childItem.number > 0) {
                console.log('子元素number大于0:', childItem);
                data.push({"property_id":childItem.id,"numbers":childItem.number})
              } else {
                console.log('子元素number等于0:', childItem);
              }
            });
          });
      console.log('goodsInfo',this.data.goodsInfo,'data',data)
    let  json_offers = JSON.stringify(data);
       if(data.length != 0) {
        getReMallShopping({
            act: 'multi_property_in_cart',
            json_data: json_offers || '',
        }).then(res => {
            console.log('添加编辑购物车-一件代发', res)
            if (res.result == 101) {
                wx.nextTick(() => {
                    getApp().Tips({
                        title: res.msg
                    })
                })
            } else {
                this.getShoppingCartList()
                wx.nextTick(() => {
                    getApp().Tips({
                        title: "商品已添加至购物车"
                    })
                })

            }
        });
       } else {
        wx.nextTick(() => {
            getApp().Tips({
                title: "请选择规格"
            })
        })
       }

        // this.setData({
        //     isSpecs: true,
        //     cartGoodDetail: this.data.goodsInfo,
        //     btnText: "加入购物车",
        //     confirmText: "handleConfirm",
        // })
      
    },
    /**
     * 完成规格选择将商品添加至购物车
     */
    handleConfirm(e) {
        console.log('传回', e)
        let data = e.detail
        this.setData({
            isSpecs: false
        })
        if (data.type == 0) { //普通
            let act = 'cart'
            if (this.data.detailType === '8') {
                act = 'new_goods_region_cart'
            }else if (this.data.detailType === '9') {
                act = 'special_price_cart'

            }
            getGoodsDetail({
                act: act,
                id: data.commodityId || '',
                propertyid: data.data.propertyid || '',
                numbers: data.count || '',

            }).then(res => {
                console.log('添加编辑购物车-一件代发', res)
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        })
                    })
                } else {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: "商品已添加至购物车"
                        })
                    })

                }
            });
        } else if (data.type == 1) { //一件代发
            ReDistributionMall({
                act: 'addEditMallCart',
                productid: data.commodityId || '',
                propertyid: data.data.productid || '',
                numbers: data.count || '',

            }).then(res => {
                console.log('添加编辑购物车-商品列表', res)
                if (res.result == 101) {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: res.msg
                        })
                    })
                } else {
                    wx.nextTick(() => {
                        getApp().Tips({
                            title: "商品已添加至购物车"
                        })
                    })

                    wx.navigateTo({
                        url: `/pages/behalf-shopping-cart/index?data=${JSON.stringify(res)}`,
                    })
                }

            });
        }

    },
    // 客服
    handleKfService() {
        wx.makePhoneCall({
            phoneNumber: "18377766475", //仅为示例，并非真实的电话号码
            success: function () {
                console.log("拨打电话成功！");
            },
            fail: function () {
                console.log("拨打电话失败！");
            },
        });

    },
    /**
     * 秒杀下单
     */
    handleJoinPay(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log(this.data.detailType)
        if (this.data.detailType == 7) {
            //新人专享
            getNavigationbar({
                act: 'unconsume_region_detail',
                id: value.id
            }).then(res => {
                res.detailType = 7
                if (res.type == null) {
                    res.type = 0
                }
                this.setData({
                    isSpecs: true,
                    cartGoodDetail: res,
                    btnText: "确认下单",
                    confirmText: "toOrder"
                })
            })
        } else {
            getGoodsDetail({
                act: 'good_detail',
                id: value.goodsid
            }).then(res => {
                this.setData({
                    isSpecs: true,
                    cartGoodDetail: res,
                    btnText: "确认下单",
                    confirmText: "toOrder"
                })
            })
        }

    },
    /**
     * 跳转下单页面
     */
    toOrder(e) {
        console.log('e',e,this.data.comityid)
        let data = {
            addressId: this.data.addressId,
            totalNumbers: e.detail.count,
            id:this.data.comityid,
            type: 'cart'
        }
        let objStr = JSON.stringify(data);
        // wx.navigateTo({
        //     url: '/pages/confirm_order_shipping/index?data=' + objStr
        // })
        wx.navigateTo({
            url: `/subpackages/pages/confirm_order_sh/index?data=` + objStr
        })
    },
    onShareAppMessage: function () {
        console.log('fenx', this.data.swiperList[0], this.data.goodsInfo.name)
        return {
            title: this.data.goodsInfo.name || this.data.goodsInfo.goodsname,
            path: `/pages/goods_detail/index?data=${JSON.stringify( this.data.params)}`, // 分享的页面路径
            imageUrl: this.data.swiperList[0].thumb, // 分享的图片链接
        }
    },
    onShareTimeline: function () {
        return {
            title: this.data.goodsInfo.name,
            path: `/pages/goods_detail/index?data=${JSON.stringify( this.data.params)}`, // 分享的页面路径
            imageUrl: this.data.swiperList[0].thumb, // 分享的图片链接
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        console.log(options)
        if (options.data) {
            const params = JSON.parse(options.data)
            this.data.params = params;
            this.setData({
                detailType: params.detailType
            })
            this.getHttpGoodsDetail(params)
            this.getAddress()
            console.log('detailType',params)
        }
       
        let res = wx.getStorageSync('USER')
        console.log('setStorageSync', res)
        this.data.obj = res
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
        this.getShoppingCartList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        const that = this
        // 清除定时器
        clearInterval(that.data.timer);
        that.setData({
            timer: null
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        const that = this
        // 清除定时器
        clearInterval(that.data.timer);
        that.setData({
            timer: null
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },


})